#!/usr/bin/env python3.2
import os,sys
import urllib.parse
import Karrigell

"""
def _log(*args):
    import sys
    for arg in args: 
        sys.stderr.write(repr(arg)+'\n')
"""

# create an application
# by default, root url is / and root directory is this directory

class BuanBuan(Karrigell.App):
    root_dir = os.path.join(os.getcwd(), 'BuanBuan')
    root_url = '/BuanBuan'
    script_url = root_url + '/index.py'
    login_url = root_url + '/admin/login.py/login'
    data_dir = os.path.join(os.path.dirname(os.getcwd()),'data','BuanBuan')
    db_path = os.path.join(data_dir,'wiki.sqlite')
    db_backend = 'sqlite'
    wikibase_module = root_url + '/modules/wikiBase_pydblite.py'
    wikidoc_module = root_url + '/modules/BuanBuan.py'
    
    # set user database
    users_path = os.path.join(data_dir,'users.sqlite')
    users_db = Karrigell.admin_db.SQLiteUsersDb(users_path)
    
    #Filters
    hidden_dirs = ['modules','templates','sessions']    
    def hidden_dir_filter(self,handler):
        """Hide directories
        Directories in hidden_dirs cannot be accessed
        directly by the client.
        """
        for hidden in self.hidden_dirs:
            hidden = self.root_url + '/' + hidden
            if handler.path_info.startswith(hidden):
                raise Karrigell.HTTP_ERROR(403)
        return None
    
    def smarturl_filter(self,handler):
        """Processes smart urls
        Smart URLs in this app have the form:
          /BuanBuan/index.py/<func>/PageName
        where <func> is one of 'edit' or 'show'.
        """
        pth = handler.path_info
        parts = urllib.parse.unquote(pth).split('/')
        newfile = None
        if len(parts) == 5 and parts[3] in ('edit','show'):
            pth = '/'.join(parts[:-1])
            handler.body['pageName'] = parts[-1]
        newfile = handler.get_file(pth)
        return newfile

    filters = [smarturl_filter,hidden_dir_filter]


# start the web server on port 80 to serve this application
Karrigell.run(apps=[BuanBuan])
